using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text.Json;
using System.Windows.Forms;
using Work.API.Dtos.DrugManagement;
using Work.ErrorCode;

namespace WinFormsApp1.DrugManagement
{
    /// <summary>
    /// 药品入库出库记录查看窗体
    /// 功能：显示指定药品的所有入库记录和出库记录
    /// 使用Tab页签分别显示入库和出库记录
    /// </summary>
    public partial class DrugRecordForm : Form
    {
        private const string ApiBaseUrl = "http://localhost:5044";
        private readonly HttpClient _httpClient;
        private readonly JsonSerializerOptions _jsonOptions;
        
        // 当前查看的药品信息
        private DrugDto _currentDrug;
        private int _drugId;
        
        // 数据缓存（避免重复加载）
        private List<DrugInboundDto> _inboundRecords;
        private List<DrugOutboundDto> _outboundRecords;
        private bool _inboundLoaded = false; // 入库记录是否已加载
        private bool _outboundLoaded = false; // 出库记录是否已加载

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="drug">要查看的药品信息</param>
        public DrugRecordForm(DrugDto drug)
        {
            if (drug == null)
            {
                throw new ArgumentNullException(nameof(drug), "药品信息不能为空");
            }

            InitializeComponent();
            _httpClient = new HttpClient { BaseAddress = new Uri(ApiBaseUrl) };
            _jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
            
            _currentDrug = drug;
            _drugId = drug.DrugId;
            _inboundRecords = new List<DrugInboundDto>();
            _outboundRecords = new List<DrugOutboundDto>();

            // 初始化药品信息显示
            InitializeDrugInfo();
            
            // 默认加载入库记录（第一个页签）
            LoadInboundRecords();
        }

        /// <summary>
        /// 初始化药品信息显示
        /// </summary>
        private void InitializeDrugInfo()
        {
            // 设置窗体标题
            this.Text = $"药品入库出库记录 - {_currentDrug.DrugName}";
            
            // 显示药品基本信息
            lblDrugName.Text = $"药品名称：{_currentDrug.DrugName}";
            lblDrugType.Text = $"类型：{_currentDrug.DrugType ?? "未设置"}";
            lblInventory.Text = $"当前库存：{_currentDrug.Inventory}";
            lblPurchasePrice.Text = $"进价：{_currentDrug.PurchasePrice:F2}";
            lblSellingPrice.Text = $"售价：{_currentDrug.SellingPrice:F2}";
        }

        /// <summary>
        /// Tab页签切换事件（按需加载数据）
        /// </summary>
        private void TabControl_SelectedIndexChanged(object? sender, EventArgs e)
        {
            if (tabControl.SelectedTab == tabInbound && !_inboundLoaded)
            {
                // 切换到入库记录页签，如果未加载则加载
                LoadInboundRecords();
            }
            else if (tabControl.SelectedTab == tabOutbound && !_outboundLoaded)
            {
                // 切换到出库记录页签，如果未加载则加载
                LoadOutboundRecords();
            }
        }

        /// <summary>
        /// 加载入库记录
        /// </summary>
        private async void LoadInboundRecords()
        {
            try
            {
                // 清空数据源，准备加载新数据
                dgvInboundRecords.DataSource = null;
                dgvInboundRecords.Columns.Clear();
                dgvInboundRecords.Rows.Clear();

                // 调用API查询入库记录（默认查询最近3个月的数据）
                DateTime? startDate = DateTime.Now.AddMonths(-3);
                var url = $"api/Drug/GetDrugInboundRecordsByDrugId?drugId={_drugId}&startDate={startDate:yyyy-MM-dd}";
                
                var response = await _httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();
                var json = await response.Content.ReadAsStringAsync();
                var apiResult = JsonSerializer.Deserialize<ApiResult<List<DrugInboundDto>>>(json, _jsonOptions);

                if (apiResult != null && apiResult.Code == ApiEnum.成功 && apiResult.Data != null)
                {
                    _inboundRecords = apiResult.Data;
                    _inboundLoaded = true;
                    RefreshInboundGridView();
                }
                else
                {
                    MessageBox.Show(apiResult?.Message ?? "查询入库记录失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    _inboundRecords = new List<DrugInboundDto>();
                    RefreshInboundGridView();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载入库记录失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                _inboundRecords = new List<DrugInboundDto>();
                RefreshInboundGridView();
            }
        }

        /// <summary>
        /// 加载出库记录
        /// </summary>
        private async void LoadOutboundRecords()
        {
            try
            {
                // 清空数据源，准备加载新数据
                dgvOutboundRecords.DataSource = null;
                dgvOutboundRecords.Columns.Clear();
                dgvOutboundRecords.Rows.Clear();

                // 调用API查询出库记录（默认查询最近3个月的数据）
                DateTime? startDate = DateTime.Now.AddMonths(-3);
                var url = $"api/Drug/GetDrugOutboundRecordsByDrugId?drugId={_drugId}&startDate={startDate:yyyy-MM-dd}";
                
                var response = await _httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();
                var json = await response.Content.ReadAsStringAsync();
                var apiResult = JsonSerializer.Deserialize<ApiResult<List<DrugOutboundDto>>>(json, _jsonOptions);

                if (apiResult != null && apiResult.Code == ApiEnum.成功 && apiResult.Data != null)
                {
                    _outboundRecords = apiResult.Data;
                    _outboundLoaded = true;
                    RefreshOutboundGridView();
                }
                else
                {
                    MessageBox.Show(apiResult?.Message ?? "查询出库记录失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    _outboundRecords = new List<DrugOutboundDto>();
                    RefreshOutboundGridView();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载出库记录失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                _outboundRecords = new List<DrugOutboundDto>();
                RefreshOutboundGridView();
            }
        }

        /// <summary>
        /// 刷新入库记录表格
        /// </summary>
        private void RefreshInboundGridView()
        {
            if (dgvInboundRecords != null)
            {
                dgvInboundRecords.DataSource = null;
                
                if (_inboundRecords == null || _inboundRecords.Count == 0)
                {
                    // 如果没有数据，显示提示信息
                    dgvInboundRecords.Rows.Clear();
                    dgvInboundRecords.Columns.Clear();
                    dgvInboundRecords.Columns.Add("Message", "提示");
                    dgvInboundRecords.Rows.Add(new object[] { "暂无入库记录" });
                    dgvInboundRecords.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                    return;
                }

                dgvInboundRecords.DataSource = _inboundRecords;
                SetInboundColumnHeaders(dgvInboundRecords);
            }
        }

        /// <summary>
        /// 刷新出库记录表格
        /// </summary>
        private void RefreshOutboundGridView()
        {
            if (dgvOutboundRecords != null)
            {
                dgvOutboundRecords.DataSource = null;
                
                if (_outboundRecords == null || _outboundRecords.Count == 0)
                {
                    // 如果没有数据，显示提示信息
                    dgvOutboundRecords.Rows.Clear();
                    dgvOutboundRecords.Columns.Clear();
                    dgvOutboundRecords.Columns.Add("Message", "提示");
                    dgvOutboundRecords.Rows.Add(new object[] { "暂无出库记录" });
                    dgvOutboundRecords.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                    return;
                }

                dgvOutboundRecords.DataSource = _outboundRecords;
                SetOutboundColumnHeaders(dgvOutboundRecords);
            }
        }

        /// <summary>
        /// 设置入库记录表格的中文列标题和格式
        /// </summary>
        private void SetInboundColumnHeaders(DataGridView dgv)
        {
            if (dgv.Columns.Count > 0)
            {
                var columnHeaders = new Dictionary<string, string>
                {
                    { "InboundId", "入库记录ID" },
                    { "DrugId", "药品ID" },
                    { "DrugName", "药品名称" },
                    { "Quantity", "入库数量" },
                    { "UnitPrice", "入库单价" },
                    { "TotalAmount", "入库总金额" },
                    { "ProductionDate", "生产日期" },
                    { "ExpirationDate", "有效日期" },
                    { "BatchNumber", "批次号" },
                    { "Supplier", "供应商" },
                    { "InboundDate", "入库日期" },
                    { "Operator", "操作人" },
                    { "Remarks", "备注" },
                    { "CreateTime", "创建时间" }
                };

                foreach (DataGridViewColumn column in dgv.Columns)
                {
                    if (columnHeaders.ContainsKey(column.Name))
                    {
                        column.HeaderText = columnHeaders[column.Name];
                    }

                    // 格式化价格和金额为两位小数
                    if (column.Name == "UnitPrice" || column.Name == "TotalAmount")
                    {
                        column.DefaultCellStyle.Format = "F2";
                        column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                    }

                    // 格式化日期列
                    if (column.Name == "InboundDate" || column.Name == "CreateTime")
                    {
                        column.DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
                    }
                    // 生产日期和有效日期可能为null，需要特殊处理
                    if (column.Name == "ProductionDate" || column.Name == "ExpirationDate")
                    {
                        column.DefaultCellStyle.Format = "yyyy-MM-dd";
                        column.DefaultCellStyle.NullValue = "未设置";
                    }
                }
            }
        }

        /// <summary>
        /// 设置出库记录表格的中文列标题和格式
        /// </summary>
        private void SetOutboundColumnHeaders(DataGridView dgv)
        {
            if (dgv.Columns.Count > 0)
            {
                var columnHeaders = new Dictionary<string, string>
                {
                    { "OutboundId", "出库记录ID" },
                    { "DrugId", "药品ID" },
                    { "DrugName", "药品名称" },
                    { "PrescriptionItemId", "处方明细ID" },
                    { "AppointmentId", "预约编号" },
                    { "PatientId", "患者ID" },
                    { "PatientName", "患者姓名" },
                    { "CardNumber", "卡号" },
                    { "RegistrationNum", "挂号编号" },
                    { "Gender", "性别" },
                    { "GenderText", "性别" },
                    { "Age", "年龄" },
                    { "IdCard", "身份证号" },
                    { "Quantity", "出库数量" },
                    { "UnitPrice", "出库单价" },
                    { "TotalAmount", "出库总金额" },
                    { "OutboundDate", "出库日期" },
                    { "Operator", "操作人" },
                    { "Remarks", "备注" },
                    { "CreateTime", "创建时间" }
                };

                foreach (DataGridViewColumn column in dgv.Columns)
                {
                    // 隐藏英文列名Gender（只显示中文的GenderText）
                    if (column.Name == "Gender")
                    {
                        column.Visible = false;
                        continue;
                    }
                    
                    if (columnHeaders.ContainsKey(column.Name))
                    {
                        column.HeaderText = columnHeaders[column.Name];
                    }
                    else
                    {
                        // 如果列名不在字典中，尝试将英文列名转换为中文
                        // 这里处理可能的其他列名
                        column.HeaderText = ConvertColumnNameToChinese(column.Name);
                    }

                    // 格式化价格和金额为两位小数
                    if (column.Name == "UnitPrice" || column.Name == "TotalAmount")
                    {
                        column.DefaultCellStyle.Format = "F2";
                        column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                    }

                    // 格式化日期列
                    if (column.Name == "OutboundDate" || column.Name == "CreateTime")
                    {
                        column.DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
                    }
                }
            }
        }
        
        /// <summary>
        /// 将英文列名转换为中文（用于处理未映射的列名）
        /// </summary>
        private string ConvertColumnNameToChinese(string columnName)
        {
            // 常见英文列名到中文的映射（作为备用）
            var commonMappings = new Dictionary<string, string>
            {
                { "Id", "ID" },
                { "Name", "名称" },
                { "Date", "日期" },
                { "Time", "时间" },
                { "Price", "价格" },
                { "Amount", "金额" },
                { "Number", "编号" },
                { "Status", "状态" },
                { "Type", "类型" },
                { "Remark", "备注" },
                { "Remarks", "备注" }
            };
            
            // 如果列名已经在字典中，直接返回
            // 否则尝试从常见映射中查找
            if (commonMappings.ContainsKey(columnName))
            {
                return commonMappings[columnName];
            }
            
            // 如果找不到映射，返回原列名（保持原样，避免显示空白）
            return columnName;
        }
        
        /// <summary>
        /// 出库记录表格Gender列的格式化事件
        /// </summary>
        private void DgvOutboundRecords_GenderFormatting(object? sender, DataGridViewCellFormattingEventArgs e)
        {
            try
            {
                if (sender is DataGridView dgv && e.ColumnIndex >= 0 && e.ColumnIndex < dgv.Columns.Count && 
                    dgv.Columns[e.ColumnIndex].Name == "Gender")
                {
                    // 处理bool类型
                    if (e.Value is bool boolValue)
                    {
                        e.Value = boolValue ? "男" : "女";
                        e.FormattingApplied = true;
                        return;
                    }
                    
                    // 处理可空bool类型
                    if (e.Value != null && e.Value is bool?)
                    {
                        bool? nullableBool = e.Value as bool?;
                        if (nullableBool.HasValue)
                        {
                            e.Value = nullableBool.Value ? "男" : "女";
                            e.FormattingApplied = true;
                            return;
                        }
                    }
                    
                    // 处理字符串类型（可能已经是格式化后的值，如GenderText）
                    if (e.Value is string)
                    {
                        // 已经是字符串，不需要格式化
                        e.FormattingApplied = false;
                        return;
                    }
                }
            }
            catch
            {
                // 忽略格式化错误，使用默认显示
                e.FormattingApplied = false;
            }
        }

        /// <summary>
        /// 刷新入库记录按钮点击事件
        /// </summary>
        private void BtnRefreshInbound_Click(object? sender, EventArgs e)
        {
            _inboundLoaded = false; // 重置加载状态，强制重新加载
            LoadInboundRecords();
        }

        /// <summary>
        /// 刷新出库记录按钮点击事件
        /// </summary>
        private void BtnRefreshOutbound_Click(object? sender, EventArgs e)
        {
            _outboundLoaded = false; // 重置加载状态，强制重新加载
            LoadOutboundRecords();
        }

        /// <summary>
        /// 关闭按钮点击事件
        /// </summary>
        private void BtnClose_Click(object? sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 入库记录表格数据错误事件处理
        /// </summary>
        private void DgvInboundRecords_DataError(object? sender, DataGridViewDataErrorEventArgs e)
        {
            // 忽略数据错误，避免显示默认错误对话框
            e.ThrowException = false;
        }

        /// <summary>
        /// 出库记录表格数据错误事件处理
        /// </summary>
        private void DgvOutboundRecords_DataError(object? sender, DataGridViewDataErrorEventArgs e)
        {
            // 忽略数据错误，避免显示默认错误对话框
            e.ThrowException = false;
        }
    }
}

